<template>
  <div class="payment">
    <div class="" v-if="step === 1">
      <div class="header"><span>请选择报账单(可多选)</span></div>
      <div class="filter-container" style="display: flex; align-items: center;">
        <el-form :inline="true" ref="filerQuery1" :model="filerQuery" class="demo-form-inline">
          <el-form-item prop="accountType" label="账户类型">
            <el-radio-group v-model="filerQuery.accountType" disabled>
              <el-radio-button label="" key="">全部</el-radio-button>
              <el-radio-button v-for="(item,index) in getEnumList('ExpenditureAccountType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="payeeType" label="收款类型">
            <el-radio-group v-model="filerQuery.payeeType">
              <el-radio-button label="" key="">全部</el-radio-button>
              <el-radio-button v-for="(item,index) in getEnumList('ExpenditureReimbursementPayeeType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="expenditureProceedsId" label="收款单位">
            <el-select v-model="filerQuery.expenditureProceedsId" class="m-2" placeholder="请选择" clearable filterable value-key="id">
              <el-option v-for="item in proceedsList" :key="item.id" :label="`${item.code} - ${item.name}`" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="proceedsBank" label="收款银行">
            <el-select v-model="filerQuery.proceedsBank" class="m-2" placeholder="请选择" clearable filterable>
              <el-option v-for="item in bankList" :key="item.id" :label="`${item.bankCode} - ${item.bankName}`" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="proceedsAccount" label="收款账号">
            <el-input v-model="filerQuery.proceedsAccount" placeholder="收款账号" @keyup.enter="handleFilter" />
          </el-form-item>
          <el-divider style="border: 0 !important;" />
          <el-form-item prop="payType" label="支付方式">
            <el-select v-model="filerQuery.payType" class="m-2" placeholder="请选择" clearable filterable>
              <el-option v-for="item in getDictList('ExpenditurePay')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="settleType" label="支付结算方式">
            <el-select v-model="filerQuery.settleType" class="m-2" placeholder="请选择" clearable filterable>
              <el-option v-for="item in getDictList('ExpenditureSettlement')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付账户">
            <el-select v-model="filerQuery.payAccount" class="m-2" placeholder="请选择" clearable filterable>
              <el-option v-for="item in accountList" :key="item.id" :label="`${item.accountCode} - ${item.accountName}`" :value="item.id"/>
            </el-select>
          </el-form-item>
          <!--
          <el-form-item label="收付标识">
            <el-radio-group v-model="filerQuery.pay">
              <el-radio-button label="" key="">全部</el-radio-button>
              <el-radio-button v-for="(item,index) in getEnumList('ExpenditurePay')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          -->
          <el-form-item>
            <el-button v-waves type="success" icon="Search" @click="handleFilter">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="">
        <el-card class="update-log">
          <el-table v-loading="listLoading"
                    :data="selectExpenditureReimbursementList"
                    row-key="id"
                    border
                    fit
                    tooltip-effect="dark"
                    @selection-change="handleSelectionChange"
                    :header-cell-class-name="headerCellClass"
                    ref="multipleTable">
            <el-table-column type="selection" width="39px" :reserve-selection="true" :selectable="selectableFn" />
            <el-table-column align="center" type="index" label="序号" width="60px" />
            <!-- <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" show-overflow-tooltip /> -->
            <el-table-column align="center" label="报账单类型" prop="reimbursementType" min-width="130px" show-overflow-tooltip>
              <template v-slot="{row}">
                <EnumTag :enum-list="getEnumList('ExpenditureReimbursementType')" :enum-key="row.reimbursementType" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="指标单编码" prop="expenditureKpiId" min-width="200px">
              <template v-slot="{row}">{{ showIdLabel(expenditureKpiList, row.expenditureKpiId, 'kpiCode') }}</template>
            </el-table-column>
            <el-table-column align="center" label="指标单名称" prop="expenditureKpiId" min-width="200px" show-overflow-tooltip>
              <template v-slot="{row}">{{ showIdLabel(expenditureKpiList, row.expenditureKpiId, 'kpiName') }}</template>
            </el-table-column>
            <el-table-column align="center" label="事前用款申请单" prop="expenditureApplicationId" min-width="140px">
              <template v-slot="{row}">{{ showIdLabel(expenditureApplicationList, row.expenditureApplicationId, 'applicationCode') }}</template>
            </el-table-column>
            <el-table-column align="center" label="报账单号" prop="reimbursementCode" min-width="120px" show-overflow-tooltip>
              <template v-slot="{row}">{{ row.reimbursementCode }}</template>
            </el-table-column>
            <el-table-column align="center" label="报账日期" prop="reimbursementDate" min-width="120px" show-overflow-tooltip>
              <template v-slot="{row}">{{ row.reimbursementDate?.substring(0, 10) }}</template>
            </el-table-column>
            <el-table-column align="center" label="收款类型" prop="payeeType" min-width="120px" show-overflow-tooltip>
              <template v-slot="{row}">
                <EnumTag :enum-list="getEnumList('ExpenditureReimbursementPayeeType')" :enum-key="row.payeeType" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="收款单位" prop="expenditureProceedsId" min-width="120px" show-overflow-tooltip>
              <template v-slot="{row}">
                {{showIdLabel(proceedsList, row.expenditureProceedsId, 'name')}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="收款银行" prop="proceedsBank" min-width="120px" show-overflow-tooltip>
              <template v-slot="{row}">
                {{showIdLabel(bankList, row.proceedsBank, 'bankName')}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="收款账号" prop="proceedsAccount" min-width="120px" show-overflow-tooltip />
            <el-table-column align="center" label="收款公务卡持卡人用户ID" prop="expenditureBusinessCardId" min-width="120px" show-overflow-tooltip>
              <template v-slot="{row}">
                {{showIdLabel(businessCardList, row.expenditureBusinessCardId, 'cardName')}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="收款公务卡开户银行" prop="businessCardBank" min-width="120px" show-overflow-tooltip>
              <template v-slot="{row}">
                {{showIdLabel(bankList, row.businessCardBank, 'bankName')}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="收款公务卡号" prop="businessCardAccount" min-width="120px" show-overflow-tooltip />
            <el-table-column align="center" label="收款摘要" prop="payeeSummary" min-width="120px" show-overflow-tooltip />
            <el-table-column align="center" label="支付方式" prop="payType" min-width="160px" show-overflow-tooltip>
              <template v-slot="{row}">
                <DictTag :dict-list="getDictList('ExpenditurePay')" :dict-key="row.payType" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="支付结算方式" prop="settleType" min-width="130px" show-overflow-tooltip>
              <template v-slot="{row}">
                <DictTag :dict-list="getDictList('ExpenditureSettlement')" :dict-key="row.settleType" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="支付账户" prop="payAccount" min-width="160px" show-overflow-tooltip>
              <template v-slot="{row}">
                <LabelTag :foreignList="accountList" :foreignIds="row.payAccount" :foreignLabel="'accountName'" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="支付收付标识" prop="pay" min-width="130px" show-overflow-tooltip>
              <template v-slot="{row}">
                <EnumTag :enum-list="getEnumList('ExpenditurePay')" :enum-key="row.pay" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="支付金额" prop="amount" min-width="120px" show-overflow-tooltip />
            <el-table-column align="center" label="支付摘要" prop="paySummary" min-width="120px" show-overflow-tooltip />
            <el-table-column align="center" label="状态" prop="state" min-width="120px" show-overflow-tooltip>
              <template v-slot="{row}">
                <EnumTag :enum-list="getEnumList('ExpenditureReimbursementState')" :enum-key="row.state" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="经济分类" prop="expenditureEconomicId" min-width="155px" show-overflow-tooltip>
              <template v-slot="{row}">{{ showIdLabel(expenditureEconomicList, row.expenditureEconomicId, 'name') }}</template>
            </el-table-column>
            <el-table-column align="center" label="会计科目" prop="expenditureSubjectId" min-width="155px" show-overflow-tooltip>
              <template v-slot="{row}">{{ showIdLabel(expenditureSubjectList, row.expenditureSubjectId, 'name') }}</template>
            </el-table-column>
            <el-table-column align="center" label="金额" prop="amount" min-width="80px" show-overflow-tooltip />
            <el-table-column align="center" label="结算方式" prop="settlement" min-width="120px" show-overflow-tooltip>
              <template v-slot="{row}">
                <DictTag :dict-list="getDictList('ExpenditureSettlement')" :dict-key="row.settlement" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="申请人部门" prop="applicationOrganizationId" min-width="255px" show-overflow-tooltip>
              <template v-slot="{row}">
                <LabelTag :foreignList="organizationList" :foreignIds="row.applicationOrganizationId" :foreignLabel="'organizationName'" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="申请人用户" prop="applicationUserId" min-width="255px" show-overflow-tooltip>
              <template v-slot="{row}">
                <LabelTag :foreignList="userList" :foreignIds="row.applicationUserId" :foreignLabel="'name'" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <div class="" style="display: flex;justify-content: center;" v-if="selectExpenditureReimbursementList.length > 0"><el-button type="primary" icon="right" @click="toNext">下一步</el-button></div>
      </div>
    </div>
    <div class="" v-if="step === 2">
      <el-form class="my-form" :model="obj" label-position="right" label-suffix=":" label-width="150px" :disabled="oper === 'view'">
        <div class="header"><span>单据信息（收款方）</span></div>
        <div class="info-content" v-if="expenditureReimbursementFirst !== undefined">
          <p class="content-head">收款类型：</p>
          <p class="content-body">{{ expenditureReimbursementFirst?.payeeType === '1' ? '单位' : '公务卡' }}</p>
        </div>
        <el-card class="update-log update-log-1" v-if="expenditureReimbursementFirst !== undefined">
          <div class="document-info"  v-if="expenditureReimbursementFirst?.payeeType === '1'">
            <div class="info-content"><p class="content-head">收款单位：</p><p class="content-body">{{ expenditureReimbursementFirst.proceedsCompany }}</p></div>
            <div class="info-content"><p class="content-head">收款银行：</p><p class="content-body">{{ showIdLabel(bankList, expenditureReimbursementFirst.proceedsBank, 'bankName') }}</p></div>
            <div class="info-content"><p class="content-head">收款账号：</p><p class="content-body">{{ expenditureReimbursementFirst.proceedsAccount }}</p></div>
            <div class="info-content"><p class="content-head">收款摘要：</p><p class="content-body">{{ expenditureReimbursementFirst.payeeSummary }}</p></div>
          </div>
          <div class="document-info"  v-if="expenditureReimbursementFirst?.payeeType === '2'">
            <div class="info-content"><p class="content-head">收款公务卡：</p><p class="content-body">{{ showIdLabel(businessCardList, expenditureReimbursementFirst.expenditureBusinessCardId, 'cardName') }}</p></div>
            <div class="info-content"><p class="content-head">收款人：</p><p class="content-body">{{ expenditureReimbursementFirst.businessCardName }}</p></div>
            <div class="info-content"><p class="content-head">收款开户行：</p><p class="content-body">{{ showIdLabel(bankList, expenditureReimbursementFirst.businessCardBank, 'bankName') }}</p></div>
            <div class="info-content"><p class="content-head">收款卡号：</p><p class="content-body">{{ expenditureReimbursementFirst.businessCardAccount }}</p></div>
            <div class="info-content"><p class="content-head">收款摘要：</p><p class="content-body">{{ expenditureReimbursementFirst.payeeSummary }}</p></div>
          </div>
        </el-card>
        <el-divider />
        <div class="header"><span>单据信息（支付方）</span></div>
        <el-card class="update-log update-log-1" v-if="expenditureReimbursementFirst !== undefined">
          <div class="document-info" >
            <div class="info-content"><p class="content-head">付款金额：</p><p class="content-body" style="color:#F56C6C; font-weight: bold;font-size: 14px;">￥{{ obj.amount.toFixed(2) }}</p></div>
            <div class="info-content"><p class="content-head">付款银行：</p><p class="content-body">{{ showIdLabel(bankList, showIdLabel(accountList, expenditureReimbursementFirst.payAccount, 'bankId'), 'bankName') }}</p></div>
            <div class="info-content"><p class="content-head">付款账号：</p><p class="content-body">{{ showIdLabel(accountList, expenditureReimbursementFirst.payAccount, 'accountName') }}</p></div>
            <div class="info-content"><p class="content-head">支付方式：</p>
              <p class="content-body">
                <DictTag :dict-list="getDictList('ExpenditurePay')" :dict-key="expenditureReimbursementFirst.payType" />
              </p>
            </div>
            <div class="info-content"><p class="content-head">付款摘要：</p><p class="content-body">{{ expenditureReimbursementFirst.paySummary }}</p></div>
          </div>
        </el-card>
        <el-divider />
        <div class="header"><span>支付令信息</span></div>
        <el-form class="document-info" ref="objForm" :model="obj" :rules="rules" label-width="160" :disabled="oper === 'view' || oper === 'exchequer'">
          <el-form-item label="支付令编码" prop="treasuryCode">
            <el-input v-model="obj.treasuryCode" placeholder="自动生成" disabled />
          </el-form-item>
          <el-form-item label="支付令名称" prop="treasuryName">
            <el-input v-model="obj.treasuryName" placeholder="请输入支付令名称" />
          </el-form-item>
          <el-form-item label="指标额度" prop="amount">
            <el-input-number v-model="obj.amount" placeholder="请输入指标额度" disabled />
          </el-form-item>
          <el-form-item label="部门经济分类" prop="expenditureEconomicId">
            <el-input v-model="obj.expenditureEconomicId" placeholder="部门经济分类" />
          </el-form-item>
          <el-form-item label="资金用途" prop="use">
            <el-input v-model="obj.use" placeholder="请输入资金用途" />
          </el-form-item>
          <el-form-item label="收款人" prop="businessCardName">
            <el-input v-model="obj.businessCardName" placeholder="请输入收款人" disabled />
          </el-form-item>
          <el-form-item label="收款人账号" prop="proceedsAccount">
            <el-input v-model="obj.proceedsAccount" placeholder="收款人账号" disabled />
          </el-form-item>
          <el-form-item label="收款人开户行" prop="payeeBank">
            <el-input v-model="obj.payeeBankDesc" placeholder="收款人开户行" disabled />
          </el-form-item>
          <el-form-item label="资金往来对象类别" prop="fundDealings">
            <el-input v-model="obj.fundDealings" placeholder="资金往来对象类别" />
          </el-form-item>
          <el-form-item label="资金类型" prop="fundType">
            <el-input v-model="obj.fundType" placeholder="资金类型" />
          </el-form-item>
          <el-form-item label="单位内部机构" prop="innerOrg">
            <el-input v-model="obj.innerOrg" placeholder="单位内部机构" />
          </el-form-item>
          <el-form-item label="支付方式(国库)" prop="payType">
            <el-select v-model="obj.payType" class="m-2" placeholder="请选择" disabled>
              <el-option v-for="item in getDictList('ExpenditurePay')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="结算方式" prop="settleType">
            <el-select v-model="obj.settleType" class="m-2" placeholder="请选择" disabled>
              <el-option v-for="item in getDictList('ExpenditureSettlement')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付业务类型" prop="businessType">
            <el-input v-model="obj.businessType" placeholder="支付业务类型" />
          </el-form-item>
          <el-form-item label="摘要" prop="summary">
            <el-input v-model="obj.summary" placeholder="请输入摘要" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="obj.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <el-divider />
        <div class="header"><span>支付令信息录入</span></div>
        <el-form class="document-info" ref="exchequerForm" :model="obj" :rules="rules" label-width="auto" :disabled="oper !== 'exchequer'">
          <el-form-item label="支付令号(已生成)" prop="exchequer">
            <el-input v-model="obj.exchequer" placeholder="请输入支付令号" style="width: 350px;" />
          </el-form-item>
        </el-form>
        <el-divider />
        <div class="header">
          <span>明细信息</span>
          <!-- <el-button type="primary" icon="Plus" style="margin-left:20px" @click="addItem">导入明细</el-button> -->
          <!-- <el-button type="primary" icon="Plus" style="margin-left:20px" @click="addItem">新增</el-button> -->
        </div>
        <el-form class="document-info" label-width="120" :disabled="oper === 'view' || oper === 'exchequer'">
          <div class="document-info" v-for="(item,index) in items" :key="index">
            <label class="form-label">明细信息{{ index + 1 }}:</label>
            <el-card class="update-log update-log-1">
              <div class="document-info">
                <el-form-item label="收款人全称">
                  <el-input v-model="item.payeeName" placeholder="请输入收款人全称" disabled />
                </el-form-item>
                <el-form-item label="收款人账号">
                  <el-input v-model="item.payeeAccount" placeholder="请输入收款人账号" disabled />
                </el-form-item>
                <el-form-item label="收款人开户行">
                  <el-input v-model="item.payeeBankDesc" placeholder="请输入收款人开户行" disabled />
                </el-form-item>
                <el-form-item label="资金用途">
                  <el-input v-model="item.use" placeholder="请输入资金用途" />
                </el-form-item>
                <el-form-item label="补贴金额">
                  <el-input-number v-model="item.amount" placeholder="请输入补贴金额" disabled />
                </el-form-item>
              </div>
              <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 1" @click="removeItem(index)">删除</el-button>
            </el-card>
          </div>
        </el-form>
      </el-form>
      <div style="text-align: center;" v-if="oper === 'add'">
        <el-button class="ico-list-btn" type="danger" @click="handleSave"><svg-icon icon-class="save" />保存支付令</el-button>
      </div>
      <div style="text-align: center;" v-if="oper === 'exchequer'">
        <el-button class="ico-list-btn" type="danger" @click="handleExchequer"><svg-icon icon-class="save" />保存国库支付令号</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import {getCurrentInstance, ref} from 'vue'
import {doGet, doPost} from '@/config/http'
import initListStore from '@/store/modules/initList'
import {
  alertErrorMsg,
  customValidator,
  getDictList,
  getEnumList,
  getListPageSize,
  notifySuccess,
  showIdLabel,
  svc
} from "@/config/common"

import {useRoute} from 'vue-router'

const { proxy: ctx } = getCurrentInstance();
const route = useRoute()

let objForm = ref(null)
let exchequerForm = ref(null)
let step = ref(0)
let expenditureReimbursementArr = ref([])
let expenditureReimbursementFirst = ref(null)
let selectExpenditureReimbursementList = ref([])

let listLoading = ref(false)

let payAmount = ref(0)

let governmentList = initListStore().governmentList
let organizationList = initListStore().organizationList
let userList = initListStore().userList
let expenditurePtypeList = initListStore().expenditurePtypeList//项目类型
let expenditureFunctionalList = initListStore().expenditureFunctionalList//功能分类
let expenditureEconomicList = initListStore().expenditureEconomicList//经济分类
let expenditureFiscalList = initListStore().expenditureFiscalList//财政项目
let expenditureSubjectList = initListStore().expenditureSubjectList//会计科目
let accountList = initListStore().accountList//
let proceedsList = initListStore().proceedsList//
let businessCardList = initListStore().businessCardList//
let bankList = initListStore().bankList//
let expenditureKpiList = initListStore().expenditureKpiList
let expenditureApplicationList = initListStore().expenditureApplicationList

let filerQuery = ref({
  accountType: '1',
  payeeType: null,
  expenditureProceedsId: null,
  proceedsCompany: null,
  proceedsBank: null,
  proceedsAccount: null,
  expenditureBusinessCardId: null,
  businessCardName: null,
  businessCardBank: null,
  businessCardAccount: null,
  payeeSummary: null,
  payType: null,
  settleType: null,
  payAccount: null,
  pay: null,
  amount: null,
  paySummary: null,
  state: '7', // 报账单
})

let emptyItem = {
  name: '', // 收款人全称
  account: '', // 收款人账号
  bank: '', // 收款人开户行
  use: '', // 资金用途
  amount: '', // 补贴金额
}

let oper = ref(route.query.oper)

let items = ref([])
let obj = ref({
  amount: null, // 申请金额
  payeeType: null, //
  applicationDate: '', // 申请日期
  applicationOrganizationId: '', // 申请人部门ID
  applicationUserId: '', // 申请人用户ID
  businessType: '', // 支付业务类型
  createBy: '', // 创建人用户ID
  createTime: '', // 创建时间
  exchequer: '', // 国库支付令号
  exchequerMessage: '', // 国库支付令消息
  fundDealings: '', // 资金往来对象类别
  fundType: '', // 资金类型
  id: '', // 主键ID
  treasuryCode: '', // 支付令编码
  treasuryName: '', // 支付令名称
  treasuryType: '0', // 支付令类型
  innerOrg: '', // 单位内部机构
  payType: '', // 支付方式(国库)
  remark: '', // 备注
  settleType: '', // 结算方式
  state: '', // 状态
  summary: '', // 摘要
})

const rules = ref({
  treasuryType: [{ required: true, validator: customValidator, min: 1, max: 20, label: '支付令类型', trigger: ['blur', 'change'] }],
  treasuryCode: [{ required: false, validator: customValidator, min: 0, max: 100, label: '支付令编码', trigger: ['blur', 'change'] }],
  treasuryName: [{ required: true, validator: customValidator, min: 1, max: 200, label: '支付令名称', trigger: ['blur', 'change'] }],
  applicationDate: [{ required: false, validator: customValidator, min: 0, max: 20, label: '申请日期', trigger: ['blur', 'change'] }],
  applicationOrganizationId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '申请人部门ID', trigger: ['blur', 'change'] }],
  applicationUserId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '申请人用户ID', trigger: ['blur', 'change'] }],
  amount: [{ required: false, validator: customValidator, min: 0, max: 13, label: '申请金额', trigger: ['blur', 'change'] }],
  state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '状态', trigger: ['blur', 'change'] }],
  fundDealings: [{ required: true, validator: customValidator, min: 1, max: 20, label: '资金往来对象类别', trigger: ['blur', 'change'] }],
  fundType: [{ required: false, validator: customValidator, min: 0, max: 20, label: '资金类型', trigger: ['blur', 'change'] }],
  innerOrg: [{ required: true, validator: customValidator, min: 1, max: 200, label: '单位内部机构', trigger: ['blur', 'change'] }],
  payType: [{ required: true, validator: customValidator, min: 1, max: 20, label: '支付方式(国库)', trigger: ['blur', 'change'] }],
  settleType: [{ required: true, validator: customValidator, min: 1, max: 20, label: '结算方式', trigger: ['blur', 'change'] }],
  businessType: [{ required: true, validator: customValidator, min: 1, max: 20, label: '支付业务类型', trigger: ['blur', 'change'] }],
  exchequer: [{ required: false, validator: customValidator, min: 0, max: 300, label: '国库支付令号', trigger: ['blur', 'change'] }],
  exchequerMessage: [{ required: false, validator: customValidator, min: 0, max: 500, label: '国库支付令消息', trigger: ['blur', 'change'] }],
  summary: [{ required: false, validator: customValidator, min: 0, max: 1000, label: '摘要', trigger: ['blur', 'change'] }],
  remark: [{ required: false, validator: customValidator, min: 0, max: 0, label: '备注', trigger: ['blur', 'change'] }],
})

const handleFilter = async () => {
  let param = filerQuery.value
  param.pageSize = getListPageSize()
  param.pageNum = 1
  let res = await doGet(svc, '/customExpenditureExpenses/queryExpenditureReimbursement', param, true);
  selectExpenditureReimbursementList.value = res['records']
}

const headerCellClass = ({row, column, rowIndex, columnIndex}) => {
  if (rowIndex === 0 && columnIndex === 0 && column.type === 'selection') {
    return 'disabledCheck'
  }
}

// 获取数据
async function initObj() {
  if (route.query.id) {
    obj.value = await doGet(svc, '/expenditure-treasury/' + route.query.id, {}, true)
    // 查询国库支付令明细
    items.value = await doGet(svc, '/expenditure-treasury-item/listByField', {field: 'expenditureTreasuryId', values: route.query.id}, false)
    //
    let expenditureReimbursementIds = []
    items.value.map(m => expenditureReimbursementIds.push(m.expenditureReimbursementId))
    expenditureReimbursementArr.value = await doGet(svc, '/customExpenditureExpenses/queryExpenditureReimbursement/' + expenditureReimbursementIds.join(','), {}, false)
    console.log('expenditureReimbursementArr.value',expenditureReimbursementArr.value)
    expenditureReimbursementFirst.value = expenditureReimbursementArr.value[0]
    console.log('expenditureReimbursementFirst.value',expenditureReimbursementFirst.value)
    step.value = 2
    if (oper.value === 'exchequer') {
      rules.value.exchequer[0].required = true
    }
  } else {
    step.value = 1
    await handleFilter()
  }
}

// const initList = async () => {
//   let p1 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false)
//   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
//   let p3 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
//   let p4 = doGet(svc, '/expenditure-ptype/page', {pageSize: getListPageSize()}, false)
//   let p5 = doGet(svc, '/expenditure-functional/page', {pageSize: getListPageSize()}, false)
//   let p6 = doGet(svc, '/expenditure-economic/page', {pageSize: getListPageSize()}, false)
//   let p7 = doGet(svc, '/expenditure-fiscal/page', {pageSize: getListPageSize()}, false)
//   let p8 = doGet(svc, '/expenditure-subject/page', {pageSize: getListPageSize()}, false)
//   let p9 = doGet(svc, '/expenditure-feetype-file/page', {pageSize: getListPageSize()}, false) // 费用类型附件
//   let p10 = doGet(svc, '/expenditure-reimbursement-item-file/page', {pageSize: getListPageSize()}, false)
//   let p11 = doGet(svc, '/expenditure-account/page', {accountType: '1', pageSize: getListPageSize()}, false)
//   let p12 = doGet(svc, '/expenditure-proceeds/page', {pageSize: getListPageSize()}, false)
//   let p13 = doGet(svc, '/expenditure-business-card/page', {pageSize: getListPageSize()}, false)
//   let p14 = doGet(svc, '/bank/page', {pageSize: getListPageSize()}, false)
//   let p15 = doGet(svc, '/expenditure-kpi/page', {pageSize: getListPageSize()}, false)
//   let p16 = doGet(svc, '/expenditure-application/page', {pageSize: getListPageSize()}, false)
//   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16])
//   governmentList.value = resArray[0]['records']
//   organizationList.value = resArray[1]['records']
//   userList.value = resArray[2]['records']
//   expenditurePtypeList.value = resArray[3]['records']
//   expenditureFunctionalList.value = resArray[4]['records']
//   expenditureEconomicList.value = resArray[5]['records']
//   expenditureFiscalList.value = resArray[6]['records']
//   expenditureSubjectList.value = resArray[7]['records']
//   accountList.value = resArray[10]['records']
//   proceedsList.value = resArray[11]['records']
//   businessCardList.value = resArray[12]['records']
//   bankList.value = resArray[13]['records']
//   expenditureKpiList.value = resArray[14]['records']
//   expenditureApplicationList.value = resArray[15]['records']
// }

initObj();
// initList()

const toNext = async () => {
  console.debug('expenditureReimbursementArr',expenditureReimbursementArr.value)
  if (expenditureReimbursementArr.value.length === 0) {
    alertErrorMsg('请选择报账单！')
    return
  }
  expenditureReimbursementArr.value.forEach(item => {
    payAmount.value += parseFloat(item.amount)
  })
  expenditureReimbursementFirst.value = expenditureReimbursementArr.value[0]
  obj.value.applicationDate = expenditureReimbursementFirst.value.reimbursementDate // 申请日期
  obj.value.applicationOrganizationId = expenditureReimbursementFirst.value.applicationOrganizationId // 申请人部门ID
  obj.value.applicationUserId = expenditureReimbursementFirst.value.applicationUserId // 申请人用户ID
  obj.value.treasuryCode = null // 支付令编码
  obj.value.treasuryName = null // 支付令名称
  obj.value.amount = payAmount.value // 申请金额
  obj.value.payeeType = expenditureReimbursementFirst.value.payeeType
  obj.value.expenditureEconomicId = expenditureReimbursementFirst.value.expenditureEconomicId // 部门经济分类
  obj.value.use = null //资金用途
  switch (obj.value.payeeType) {
    case '1':
      obj.value.businessCardName = expenditureReimbursementFirst.value.proceedsCompany // 收款单位
      obj.value.proceedsAccount = expenditureReimbursementFirst.value.proceedsAccount // 收款单位账号
      obj.value.payeeBank = expenditureReimbursementFirst.value.proceedsBank // 收款单位开户行
      obj.value.payeeBankDesc = bankList.value.filter(item => item.id === expenditureReimbursementFirst.value.proceedsBank)[0]?.bankName
      break
    case '2':
      obj.value.businessCardName = expenditureReimbursementFirst.value.businessCardName // 收款人
      obj.value.proceedsAccount = expenditureReimbursementFirst.value.businessCardAccount // 收款人账号
      obj.value.payeeBank = expenditureReimbursementFirst.value.businessCardBank // 收款人开户行
      obj.value.payeeBankDesc = bankList.value.filter(item => item.id === expenditureReimbursementFirst.value.businessCardBank)[0]?.bankName
      break
  }
  obj.value.fundDealings = null // 资金往来对象类别
  obj.value.fundType = expenditureReimbursementFirst.value.fundType // 资金类型
  obj.value.innerOrg = null // 单位内部机构
  obj.value.payType = expenditureReimbursementFirst.value.payType // 支付方式(国库)
  obj.value.settleType = expenditureReimbursementFirst.value.settleType // 结算方式
  obj.value.businessType = null // 支付业务类型
  obj.value.exchequer = null // 支付令号(已生成)
  obj.value.exchequerMessage = null // 国库支付令消息
  expenditureReimbursementArr.value.map(m => {
    let o = {
      expenditureReimbursementId: m['id'],
      use: null,
      amount: m['amount'],
    }
    switch (m['payeeType']) {
      case "1":
        o.payeeName = m['proceedsCompany']
        o.payeeAccount = m['proceedsAccount']
        o.payeeBank = m['proceedsBank']
        o.payeeBankDesc = bankList.value.filter(item => item.id === m['proceedsBank'])[0]?.bankName
        break
      case "2":
        o.payeeName = m['businessCardName']
        o.payeeAccount = m['businessCardAccount']
        o.payeeBank = m['businessCardBank']
        o.payeeBankDesc = bankList.value.filter(item => item.id === m['businessCardBank'])[0]?.bankName
        break
    }
    items.value.push(o)
  })
  step.value = 2
}

const handleSelectionChange = (data) => {
  expenditureReimbursementArr.value = data
}

const selectableFn = (row) => {
  let data = expenditureReimbursementArr.value
  if (data.length >= 1) {
    return row.proceedsAccount === data[0].proceedsAccount
          && row.proceedsCompany === data[0].proceedsCompany
          && row.payAccount === data[0].payAccount
          && row.payType === data[0].payType
  } else  {
    if (filerQuery.value.proceedsAccount && filerQuery.value.proceedsCompany && filerQuery.value.payAccount && filerQuery.value.payType) {
      return row.proceedsAccount === filerQuery.value.proceedsAccount
            && row.proceedsCompany === filerQuery.value.proceedsCompany
            && row.payAccount === filerQuery.value.payAccount
            && row.payType === filerQuery.value.payType
    } else {
      return true
    }
  }
}

// 新增明细信息
const addItem = () => {
  let item = Object.assign({}, emptyItem)
  items.value.push(item)
}

// 删除明细信息
const removeItem = (index) => {
  items.value.splice(index, 1)
}

const buildObj = () => {
  let o = obj.value
  o.items = items.value
  return o
}

const handleSave = async () => {
  console.debug('objForm',objForm.value)
  let v = await objForm.value.validate().catch((err)=>{return err})
  if (v !== true) {
    alertErrorMsg('表单验证不通过，请检查数据。')
    return
  }
  let o = buildObj()
  doPost(svc, '/customDisbursement/saveExpenditureTreasury', o).then(() => {
    notifySuccess('操作成功')
    ctx.$tab.closeOpenPage({ path: '/expenditure/disbursement/expenditureTreasury', query: {} })
  })
}

const handleExchequer = async () => {
  let v = await exchequerForm.value.validate().catch((err)=>{return err})
  if (v !== true) {
    alertErrorMsg('表单验证不通过，请检查数据。')
    return
  }
  let o = {
    expenditureTreasuryId: obj.value.id,
    exchequer: obj.value.exchequer,
    exchequerMessage: '',
  }
  doPost(svc, '/customDisbursement/exchequerExpenditureTreasury', o).then(() => {
    notifySuccess('操作成功')
    ctx.$tab.closeOpenPage({ path: '/expenditure/disbursement/expenditureTreasury', query: {} })
  })
}
</script>
<style scoped>
td,th {
  padding: 20px 0;
}
.form-label {
  font-size: 16px;
  color: #337ecc;
  line-height: 32px;
  padding: 0 12px 0 0;
  box-sizing: border-box;
  width: 200px;
  font-weight: bold;
  margin: 10px 0;
}
.update-log {
  width: 100%;
  margin: 30px 0;
}
.update-log-1 {
  margin-top: 0;
}
.document-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  color: #606266;
}
.info-content {
  font-size: 14px;
  display: flex;
}
.info-content .content-head {
  width: 120px;
  text-align: right;
  font-weight: 700;
}
.info-content .content-body {
  text-align: left;
  width: 300px;
}
.update-log {
  width: 100%;
  margin-bottom: 30px;
}
.update-log-1 {
  margin-top: 0;
}
.form-label-1 span {
  font-size: 1.25rem;
}
.header {
  width: 100%;
  height: 30px;
  line-height: 30px;
  border-left: 10px solid #67C23A;
  margin: 10px 0;
  display: flex;
  align-items: center;
}
.header span {
  padding-left: 15px;
  color: #409EFF;
  font-size: 20px;
  font-weight: bold;
}
.ico-list-btn {
  background: rgba(0,0,0,.7);
  width: 150px;
  height: 45px;
  outline:none;
  border-color: rgba(0,0,0,.5);
  margin: 0 auto;
}
.payment {
  margin: 20px;
}
/* 去掉全选按钮 */
.el-table .disabledCheck .cell .el-checkbox__inner {
  display: none !important;
}
.el-table .disabledCheck .cell::before{
  content: '选择';
  text-align: center;
  line-height: 37px;
}
</style>
